﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace System.Web.Mvc
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class LExceptionAttribute : FilterAttribute, IExceptionFilter
    {

        /// <summary>
        /// 异常返回页面类型
        /// </summary>
        public ViewResultEnum ViewResultEnum { get; set; }

        /// <summary>
        /// 捕获的异常类型
        /// </summary>
        public Type HandleException { get; set; }

        public void OnException(ExceptionContext filterContext)
        {
            //string controller = filterContext.RouteData.Values["controller"] as string;
            //string action = filterContext.RouteData.Values["action"] as string;


            filterContext.Controller.ViewData["ErrorMessage"] = filterContext.Exception.Message;

            foreach (string key in filterContext.HttpContext.Request.Form.Keys)
            {
                filterContext.Controller.ViewData.Add(key, filterContext.HttpContext.Request.Form[key]);
            }

           // filterContext.Controller.ViewData.ModelState.AddModelError("Code", filterContext.Exception.Message);

            if (ViewResultEnum == ViewResultEnum.ViewResult)
            {
                filterContext.Result =
                    new ViewResult()
                        {
                            ViewName = ((RouteData)filterContext.RouteData).Values["action"].ToString(),
                            TempData = filterContext.Controller.TempData,
                            ViewData = filterContext.Controller.ViewData
                        };
            }
            else if (ViewResultEnum == ViewResultEnum.PartialViewResult)
            {
                filterContext.Result =
                   new PartialViewResult()
                   {
                       ViewName = ((RouteData)filterContext.RouteData).Values["action"].ToString(),
                       TempData = filterContext.Controller.TempData,
                       ViewData = filterContext.Controller.ViewData
                   };
            }
            else
            {
                filterContext.Result =
                    new ViewResult()
                        {
                            ViewName = "Error",
                            ViewData = filterContext.Controller.ViewData
                        };
            }





            filterContext.ExceptionHandled = true;
        }
    }

    public enum ViewResultEnum
    {
        None = 0,
        ViewResult,
        PartialViewResult
    }
}
